# -*- coding: utf-8 -*-

import os
import urllib
import pickle

from google.appengine.ext import db
from kay.conf import settings

from gdata import gauth
from kay.utils import url_for
from kay.utils import local
from kay_authsub.models import Token

AUTHSUB_TOKEN_PROPERTY_NAME = "authsub_token"

def get_authsub_token_from_request(request):
  if hasattr(request, 'user'):
    prop = getattr(request.user.__class__, AUTHSUB_TOKEN_PROPERTY_NAME, None)
    if isinstance(prop, db.BlobProperty):
      p_token = getattr(request.user, AUTHSUB_TOKEN_PROPERTY_NAME, None)
    else:
      db_token = Token.get_by_key_name(AUTHSUB_TOKEN_PROPERTY_NAME,
                                       parent=request.user)
      if db_token:
        p_token = db_token.token
      else:
        p_token = None
    if p_token:
      return pickle.loads(p_token)

def save_authsub_token(authsub_token, request):
  p_token = pickle.dumps(authsub_token)
  if hasattr(request, 'user'):
    prop = getattr(request.user.__class__, AUTHSUB_TOKEN_PROPERTY_NAME, None)
    if isinstance(prop, db.BlobProperty):
      setattr(request.user, AUTHSUB_TOKEN_PROPERTY_NAME, p_token)
      request.user.put()
    else:
      db_token = Token(token=p_token, parent=request.user,
                       key_name=AUTHSUB_TOKEN_PROPERTY_NAME)
      db_token.put()
  else:
    raise RuntimeError("request.user must be present.")

def delete_authsub_token(request):
  if hasattr(request, 'user'):
    prop = getattr(request.user.__class__, AUTHSUB_TOKEN_PROPERTY_NAME, None)
    if isinstance(prop, db.BlobProperty):
      setattr(request.user, AUTHSUB_TOKEN_PROPERTY_NAME, None)
      request.user.put()
    else:
      db.delete(db.Key.from_path(Token.kind(), AUTHSUB_TOKEN_PROPERTY_NAME,
                                 parent=request.user.key()))

def get_authsub_url(next=None):
  if next is None:
    next = local.request.url
  secure = not is_devserver
  key_file = getattr(settings, "AUTHSUB_PRIVATE_KEY", None)
  if key_file is None:
    secure = False
  scopes = getattr(settings, "AUTHSUB_SCOPES", ())
  url = gauth.generate_auth_sub_url(
    url_for("kay_authsub/receive_authsub_token", _external=True, next=next),
    scopes, secure=secure)
  return str(url)

def get_revoke_authsub_url(next=None):
  if next is None:
    next = local.request.url
  return url_for("kay_authsub/revoke_authsub_token", next=next)

is_devserver = os.environ['APPLICATION_ID'] == 'test' or \
    ('SERVER_SOFTWARE' in os.environ and \
       os.environ['SERVER_SOFTWARE'].startswith('Dev'))

